/**
 * 交易对信息 
 */
let trade = {};
var symbols = [] ;
var currentPair = {};   
var DEFAULT_COIN = getUrlKey("symbol")?getUrlKey("symbol"):'BTCUSDT';
var global_lang = "CN";
var userInfo = {} ; 
var assembles = {};
var userActiveOrders = []; 
var userHistoryOrders = []; 
function getUrlKey(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}
/**
 * 组装交易对信息 
 * @returns
 */
trade.assembleSymbols = function(msg) {
    switch (msg.constructor.name) { 
        case 'MasterDataResponse': 
            var pairs =  msg.pairs ; // 支持的交易对 
            var currencies  = msg.currencies ; // 所有币种信息 
            DEFAULT_COIN = getUrlKey("symbol")?getUrlKey("symbol"):'BTCUSDT';
            symbols = [] ;  
            for (var i = 0; i < pairs.length; i++) { 
                 var symbol  = {}  ;
                 var pair = pairs[i] ; 
                 var baseCurrencyId = pair.baseCurrencyId ;  
                 var quoteCurrencyId = pair.quoteCurrencyId ; 
                 for(var j = 0; j < currencies.length; j++){
                     if(baseCurrencyId === currencies[j].currencyId || quoteCurrencyId === currencies[j].currencyId ){
                         if(baseCurrencyId === currencies[j].currencyId){
                             symbol.baseCurrencyName = currencies[j].code  ; //基础币种名称
                             symbol.baseCurrencyPrecision = currencies[j].precision ; // 基础币种小数位数
                             symbol.region = currencies[j].region ;  //  P - 主流区; I - 创新区 
                         }else{
                             symbol.quoteCurrencyName = currencies[j].code  ; // 计价币种名称
                             symbol.quoteCurrencyPrecision = currencies[j].precision ; // 计价币种小数位数
                         } 
                     }
                 }
                 symbol.closeBtc = 0 ; // 1个base currency对BTC的最新价格? 
                 symbol.closeCny = 0 ; // 此处获取的应该是最新价折合成CNY的价格，而不是单个折合成CNY的价格
                 symbol.closeUsd = 0 ;   
                 symbol.baseCurrencyId  = baseCurrencyId ; // 基础币种ID
                 symbol.quoteCurrencyId  = quoteCurrencyId ;  // 计价币种ID  
                 symbol.minNotional = pair.minNotional ; //最小订单价值，量*价格
                 symbol.maxSize = pair.maxSize ; // 最大下单量
                 symbol.minSize = pair.minSize ; // 最小下单量
                 symbol.maxPrice = pair.maxPrice ; // 最大下单价格
                 symbol.minPrice = pair.minPrice ; // 最小下单价格
                 symbol.tradable = pair.tradable ; // 当前是否可交易
                 symbol.priceDisplayDp = pair.priceDisplayDp ; //价格显示小数位数
                 symbol.sizeDisplayDp = pair.sizeDisplayDp ; //量显示小数位数
                 symbol.symbol = pair.symbol ; //交易对名称 ETHUSDT
                 symbol.pairId = pair.pairId ; // 交易对ID  
                 symbol.high = 0 ; 
                 symbol.open = 0 ; 
                 symbol.low = 0	 ; 
                 symbol.close = 0 ; 
                 symbol.price = 0 ; 
                 symbol.volume = 0 ; 
                 symbol.changeFor24H = 0 ; // 24小时涨跌幅 
                 symbol.isWatch = false ; 
                 symbol.takerCommission = 0 ; // 限价交易手续费比例
                 symbol.makerCommission = 0 ;  // 市价交易手续
                 if(symbol.symbol == DEFAULT_COIN){
                    currentPair = symbol  ;
                }
                 symbols.push(symbol);
            } 
            break ; 
        case 'SymbolListResponse':  
            for (var i = 0; i < msg.quotes.length; i++) { 
                 for(var j = 0 ; j <symbols.length ; j++){
                     if(msg.quotes[i].symbol === symbols[j].symbol ){
                         symbols[j].high = msg.quotes[i].high ; 
                         symbols[j].open = msg.quotes[i].open ; 
                         symbols[j].low = msg.quotes[i].low	 ; 
                         symbols[j].close = msg.quotes[i].close ; 
                         symbols[j].price = msg.quotes[i].price ; 
                         symbols[j].volume = msg.quotes[i].volume.toFixed(2) ; 
                         symbols[j].closeBtc = msg.quotes[i].closeBtc ; // 1个base currency对BTC的最新价格
                         symbols[j].closeCny = msg.quotes[i].closeCny ; 
                         symbols[j].closeUsd = msg.quotes[i].closeUsd ; 
                         symbols[j].closeDefeat=Number(global_lang=='EN'?msg.quotes[i].closeUsd:msg.quotes[i].closeCny).toFixed(4);
                         if( msg.quotes[i].open  == 0 ){
                             symbols[j].changeFor24H = 0  ; 
                         }else{
                             symbols[j].changeFor24H = Number((msg.quotes[i].price-msg.quotes[i].open)/msg.quotes[i].open * 100 ).toFixed(2) ; // 24小时涨跌幅
                         }
                         if(symbols[j].symbol === DEFAULT_COIN){
                            currentPair = symbols[j]  ;
                        }
                         /*var timestamp =Date.parse(new Date());
                         var newTimeStamp = (timestamp - msg.quote[i].toTime)/1000/60/60;
                         if(newTimeStamp>=24){
                             symbols[j].changeFor24H = 0  ;
                         }*/
                         break; 
                     }
                 }
            } 
            break ; 
        case 'QuoteUpdateResponse':  
            for(var j = 0 ; j <symbols.length ; j++){
                 if(msg.quote.symbol === symbols[j].symbol ){
                     symbols[j].high = msg.quote.high ; 
                     symbols[j].open = msg.quote.open ; 
                     symbols[j].low = msg.quote.low	 ; 
                     symbols[j].close = msg.quote.close ; 
                     symbols[j].price = msg.quote.price ; 
                     symbols[j].volume = msg.quote.volume.toFixed(2) ; 
                     if( msg.quote.open  == 0 ){
                         symbols[j].changeFor24H = 0  ; 
                     }else{
                         symbols[j].changeFor24H = Number((msg.quote.price-msg.quote.open)/msg.quote.open * 100).toFixed(2) ; // 24小时涨跌幅
                     }
                     /*var timestamp =Date.parse(new Date());
                     var newTimeStamp = (timestamp - msg.quote.toTime)/1000/60/60;
                     if(newTimeStamp>=24){
                         symbols[j].changeFor24H = 0  ;
                     }*/
                     symbols[j].closeBtc = msg.quote.closeBtc ; // 1个base currency对BTC的最新价格
                     symbols[j].closeCny = msg.quote.closeCny ; 
                     symbols[j].closeUsd = msg.quote.closeUsd ; 
                     if(symbols[j].symbol === DEFAULT_COIN){
                        currentPair = symbols[j]  ;
                    }
                     break; 
                 }
             }
        break ; 
        case 'WatchListResponse':  
            for(var j = 0 ; j <symbols.length ; j++){
                 symbols[j].isWatch = false  ;   
             }
            for(var i = 0 ; i <msg.quotes.length ; i++){
                for(var j = 0 ; j <symbols.length ; j++){   
                     if(msg.quotes[i].symbol === symbols[j].symbol ){
                         symbols[j].isWatch = true  ; // 自选
                          break; 
                     }
                 }
            }
        break ;
        case 'QuoteResponse':  
            for(var j = 0 ; j <symbols.length ; j++){
                 if(msg.quote.symbol === symbols[j].symbol ){
                     symbols[j].makerCommission = msg.makerCommission ; 
                     symbols[j].takerCommission = msg.takerCommission ; 
                     symbols[j].high = msg.quote.high ; 
                     symbols[j].open = msg.quote.open ; 
                     symbols[j].low = msg.quote.low	 ; 
                     symbols[j].close = msg.quote.close ; 
                     symbols[j].price = msg.quote.price ; 
                     symbols[j].volume = msg.quote.volume.toFixed(2) ; 
                     if( msg.quote.open  == 0 ){
                         symbols[j].changeFor24H = 0  ; 
                     }else{
                         symbols[j].changeFor24H = Number((msg.quote.price-msg.quote.open)/msg.quote.open * 100).toFixed(2) ; // 24小时涨跌幅
                     }
                     /*var timestamp =Date.parse(new Date());
                     var newTimeStamp = (timestamp - msg.quote.toTime)/1000/60/60;
                     if(newTimeStamp>=24){
                         symbols[j].changeFor24H = 0  ;
                     }*/
                     symbols[j].closeBtc = msg.quote.closeBtc ; // 1个base currency对BTC的最新价格
                     symbols[j].closeCny = msg.quote.closeCny ; 
                     symbols[j].closeUsd = msg.quote.closeUsd ; 
                     if(symbols[j].symbol === DEFAULT_COIN){
                        currentPair = symbols[j]  ;
                     }
                     break; 
                 }
             }
        break ;
        case 'WatchListEditResponse':  
            console.log('增加或删除自选响应',msg) ; 
        break ;
    }
    return  symbols ;
}

trade.getCurrentPair = function(){
    return currentPair;
}
function changeDecimalBuZero(number, bitNum) {
    /// <summary>
    /// 小数位不够，用0补足位数
    /// </summary>
    /// <param name="number">要处理的数字</param>
    /// <param name="bitNum">生成的小数位数</param>
    var f_x = parseFloat(number);
    if (isNaN(f_x)) {
        return 0;
    }
    var s_x = number.toString();
    var pos_decimal = s_x.indexOf('.');
    if (pos_decimal < 0) {
        pos_decimal = s_x.length;
        s_x += '.';
    }
    while (s_x.length <= pos_decimal + bitNum) {
        s_x += '0';
    }
    return s_x;
}
//刷新出售挂单
trade.refreshDepthAsksData = function(data){
    let priceDisplayDp = currentPair.priceDisplayDp;
    let sizeDisplayDp = currentPair.sizeDisplayDp;
    let sellList = [];
    if(data['asks']){
        var asks = data['asks'];
        var sellmax		= 0	;
        asks.forEach(function(e) {
            if(e.size>sellmax)
            sellmax = e.size
        });
        asks.forEach(function(DmDepthItem, i) {
            let price	= Number(DmDepthItem.price.toFixed(priceDisplayDp));
            let size	= Number(DmDepthItem.size.toFixed(sizeDisplayDp));
            DmDepthItem.price = changeDecimalBuZero(price,priceDisplayDp);
            DmDepthItem.size = changeDecimalBuZero(size,sizeDisplayDp);
            DmDepthItem.totalprice	= Number((DmDepthItem.size*DmDepthItem.price).toFixed(priceDisplayDp));
            DmDepthItem.width	= DmDepthItem.size/sellmax*100+'%';
            DmDepthItem.title	= i+1;
            if(DmDepthItem.has){
                DmDepthItem.has	=true
            }else{
                DmDepthItem.has	=false
            }
            // if( i == 0 && !$("#limit_buy_price").val()){
            //     $("#limit_buy_price").val(DmDepthItem.price); 
            //     on_input_ask_rate() ;
            // }
        })
        //Vue.set(trade_Vue,"sellOrders",asks.reverse());
    }
    return asks.reverse();
}
//刷新购买挂单
trade.refreshDepthBidsData = function(data){
    let priceDisplayDp = currentPair.priceDisplayDp;
    let sizeDisplayDp = currentPair.sizeDisplayDp;
    let sellList = [];
    if(data['bids']){
        var bids = data['bids'];
        var sellmax		= 0	;
        bids.forEach(function(e) {
            if(e.size>sellmax)
            sellmax = e.size
        });
        bids.forEach(function(DmDepthItem, i) {
            let price	= Number(DmDepthItem.price.toFixed(priceDisplayDp));
            let size	= Number(DmDepthItem.size.toFixed(sizeDisplayDp));
            DmDepthItem.price = changeDecimalBuZero(price,priceDisplayDp);
            DmDepthItem.size = changeDecimalBuZero(size,sizeDisplayDp);
            DmDepthItem.totalprice	= Number((DmDepthItem.size*DmDepthItem.price).toFixed(priceDisplayDp));
            DmDepthItem.width	= DmDepthItem.size/sellmax*100+'%';
            DmDepthItem.title	= i+1;
            if(DmDepthItem.has){
                DmDepthItem.has	=true
            }else{
                DmDepthItem.has	=false
            }
            //  if( i == 0 && !$("#limit_sell_price").val()){
            //     $("#limit_sell_price").val(DmDepthItem.price); 
            //     on_input_bid_rate() ;
            //   }
        }) 
        //Vue.set(trade_Vue,"sellOrders",bids.reverse());
    }
    return bids;
}

// 刷新当前交易对的行情
trade.refreshCurrentPair = function(){
    var _class = currentPair.changeFor24H > 0 ? 'up' : 'down' ;  
    var change = currentPair.changeFor24H > 0 ? '+'+currentPair.changeFor24H : currentPair.changeFor24H ;
    var quote = currentPair;
    if(currentPair.changeFor24H == 0){
        change = Number(currentPair.changeFor24H).toFixed(2) ; 
        _class = '' ; 
    }
    quote.change=change;
    quote._class=_class;
    quote.taker_commission=Number(currentPair.takerCommission)*100+'%';
    quote.marker_commission=Number(currentPair.makerCommission)*100+'%';
    quote.close=Number(Number(currentPair.close).toFixed(currentPair.priceDisplayDp));
    quote.closeDefeat=Number(global_lang=='EN'?currentPair.closeUsd:currentPair.closeCny).toFixed(4);
    quote.low=Number(Number(currentPair.low).toFixed(currentPair.priceDisplayDp));
    quote.high=Number(Number(currentPair.high).toFixed(currentPair.priceDisplayDp));
    quote.volume=Math.ceil(Number(currentPair.volume));
    return quote;
}

/**
 * 用户信息
 * @param msg
 * @returns
 */
trade.assembleUserInfo = function(msg){
	switch (msg.constructor.name) { 
		case 'UserLoginResponse':
			userInfo  = msg ; 
			break
		case  'UserAccountUpdateResponse':
			for(var i = 0 ; i <userInfo.accounts.length ; i++){
				if(userInfo.accounts[i].accountId == msg.account.accountId){
					userInfo.accounts[i] = msg.account ; 
					break ; 
				}
			}
			break ; 
	}
	return userInfo ; 
}
/**
 * 预测合约用户信息
 * @param msg
 * @returns
 */
trade.futureAssembleUserInfo = function(msg){
	symbols.forEach(function(obj) {
        if(obj.symbol==DEFAULT_COIN)
            msg.accounts.forEach(function(e) {
                if(e.currencyId==obj.quoteCurrencyId){
                    assembles.dmUserAccount=e;
                    assembles.quoteCurrencyName = obj.quoteCurrencyName;
                    assembles.available = Number(e.available);
                    assembles.rebate = Number(e.rebate)
                    //资金流水请求
                    //分析
                }
        })
    })
	return assembles ; 
}

/**
 * 更新用户账号信息 
 * @returns
 */
trade.refreshAccountInfo = function(){
    for(var i = 0 ; i < symbols.length ; i++ ){
       if(symbols[i].symbol === DEFAULT_COIN){ // 只更新当前页面的交易对的账户信息
           var accountInfo = {base_available:0,quote_available:0};
           for(var j = 0 ; j < userInfo.accounts.length ; j++ ){
               if(userInfo.accounts[j].currencyId == symbols[i].baseCurrencyId){
                   accountInfo.base_available=Number(Number(userInfo.accounts[j].available).toFixed(symbols[i].sizeDisplayDp));
               }
               if(userInfo.accounts[j].currencyId == symbols[i].quoteCurrencyId){
                   accountInfo.quote_available=Number(Number(userInfo.accounts[j].available).toFixed(symbols[i].priceDisplayDp));
               }
           }
        }
    }
    return accountInfo;
}


/**
 * 
 * 组装用户订单信息
 * @returns
 */
trade.assembleUserOrders = function(msg){
		switch (msg.constructor.name) {   
			case 'OrderResponse':   
				userActiveOrders = [] ; 
				userHistoryOrders = [] ; 
				for(var i = 0 ; i <msg.orders.length ; i++){ 
					  var order = msg.orders[i] ;  
					  if( order.isActive ){ 
                          order.createdTime = userDate(order.createdTime);
						  userActiveOrders.push(order) ; 
					  }else{
                            order.createdTime = userDate(order.createdTime);
						  userHistoryOrders.push(order) ; 
					  } 
				 }
			break ;
			case 'OrderUpdateResponse':    
				var isExist = false ; 
				for(var i = 0 ; i < userActiveOrders.length ; i++){
					 if(userActiveOrders[i].orderId == msg.order.orderId  ){
						 if(msg.order.isActive){
                            msg.order.createdTime = userDate(msg.order.createdTime);
							 userActiveOrders[i] = msg.order ; 
							 isExist = true ; 
							 break  ; 
						 }else{
                             console.log('订单不再活跃,移除',msg.order);
                             msg.order.createdTime = userDate(msg.order.createdTime);
							 userActiveOrders.splice(i,1) 
							 //(索引位置, 要删除元素的数量, 元素),删除为0则为插入数据
							 userHistoryOrders.splice(0,0,msg.order)  ;  
							 isExist = true ; 
							 break; 
						 }
					 }
				 }
				if(!isExist){
                    if(msg.order.isActive){ // 提交后部分成交
                        msg.order.createdTime = userDate(msg.order.createdTime);
						userActiveOrders.splice(0,0,msg.order)  ;  
                    }else{ // 提交后全部成交
                        msg.order.createdTime = userDate(msg.order.createdTime);
						 userHistoryOrders.splice(0,0,msg.order)   ; 
					} 
				}  
			break ;
			case 'CancelOrderResponse':   
				for(var i = 0 ; i < userActiveOrders.length ; i++){
					 if(userActiveOrders[i].orderId == msg.orderId  ){ 
						 userActiveOrders.splice(i,1)
						 break  ; 
					 } 
				 } 
			break ;
    } 
    return {userActiveOrders,userHistoryOrders};
}

/**
 * 刷新成交
 * @param data
 * @returns
 */
trade.refreshTradeHistory = function(data){
	var priceDisplayDp = currentPair.priceDisplayDp ;  
    var sizeDisplayDp = currentPair.sizeDisplayDp ; 
    data.trades.forEach((item,i)=>{
        item.time = userTime(Number(item.time));
        let price = Number(Number(item.price).toFixed(priceDisplayDp));
        let size = Number(Number(item.size).toFixed(sizeDisplayDp));
        item.price = changeDecimalBuZero(price,priceDisplayDp);
        item.size = changeDecimalBuZero(size,sizeDisplayDp);
    })
    return data.trades;
}
function userDate(uData){
    var myDate = new Date(uData);
    var year = myDate.getFullYear().toString();
    var month = myDate.getMonth() + 1;
    if(month<10){month='0'+month}
    var day = myDate.getDate();
    if(day<10){day='0'+day}
    var hours = myDate.getHours();
    if(hours<10){hours='0'+hours}
    var minutes = myDate.getMinutes();
    if(minutes<10){minutes='0'+minutes}
    var seconds = myDate.getSeconds();
    if(seconds<10){seconds='0'+seconds}
    return  year + '-' + month + '-' + day +' '+ hours + ':' + minutes + ':' +seconds;
  }
function userTime(uData){
    var myDate = new Date(uData);
    var year = myDate.getFullYear().toString().substr(2, 2);
    var month = myDate.getMonth() + 1;
    if(month<10){month='0'+month}
    var day = myDate.getDate();
    if(day<10){day='0'+day}
    var hours = myDate.getHours();
    if(hours<10){hours='0'+hours}
    var minutes = myDate.getMinutes();
    if(minutes<10){minutes='0'+minutes}
    var seconds = myDate.getSeconds();
    if(seconds<10){seconds='0'+seconds}
    return    hours + ':' + minutes + ':' + seconds;
  }

/**
 * 刷新用户挂单
 * 
 * */  
trade.refreshOrder = function(){
    var priceDisplayDp = currentPair.priceDisplayDp; ; 
    var sizeDisplayDp = currentPair.sizeDisplayDp ;   
    userActiveOrders.forEach((item,index)=>{
        item.time = userDate(item.createdTime);
        item.price = Number(Number(item.price).toFixed(priceDisplayDp));
        item.size = Number(Number(item.size).toFixed(sizeDisplayDp));
        item.filledSize = Number(Number(item.filledSize).toFixed(sizeDisplayDp))
    })
    return userActiveOrders;
}
trade.refreshOrder = function(){
    var priceDisplayDp = currentPair.priceDisplayDp; ; 
    var sizeDisplayDp = currentPair.sizeDisplayDp ;   
    userActiveOrders.forEach((item,index)=>{
        item.time = userDate(item.createdTime);
        item.price = Number(Number(item.price).toFixed(priceDisplayDp));
        item.size = Number(Number(item.size).toFixed(sizeDisplayDp));
        item.filledSize = Number(Number(item.filledSize).toFixed(sizeDisplayDp))
    })
    return userActiveOrders;
}

export default trade;